<?php
namespace Home\Controller;
use Think\Controller;
class LoginController extends Controller {
    public function login(){
//        echo md5('admin123*&*_asdf44');
        //如果登录过了就让他直接跳到首页
        if(session('adminUser')){
            $this->redirect('/Home/Index/index');
        }
        $this->display();
    }

    //退出
    public function logout(){
        session(null);   //清空当前的session
        $this->redirect('login/login');
    }
    //生成验证验
    public function vcode()
    {
        $Verify = new \Think\Verify();
        $Verify->imageW = 100;
        $Verify->imageH = 38;
        $Verify->fontSize = 14;
        $Verify->useNoise = false;
        $Verify->length = 4;
        $Verify->entry();
    }
    //验证验证码
    public function check_verify($code, $id = '')
    {
        $verify = new \Think\Verify();
        return $verify->check($code, $id);
    }

    //ajax检测验证码是否正确
    public function yzm()
    {
        if (IS_POST) {
            $ma = $_POST['yzm'];
            if ($this->check_verify($ma)) {
                $this->ajaxReturn(true);
            } else {
                $this->ajaxReturn(false);
            }
        }
    }


    public function check()
    {
        $username = trim(I('post.username'));
        $password = trim(I('post.password'));
        if (!$username) {
            return show(0, '用户名不能为空');
        }
        if (!$password) {
            return show(0, '密码不能为空');
        }
        $data = M('Admin')->where('username="' . $username . '"')->find();  //通过username将这个用户的数据都取出
        if (!$data) {
            return show(0, '用户不存在');
        }
        if ($data['is_use'] == '0') {
            return show(0, '用户已经被禁止登陆');
        }
        if ($data['password'] != getMd5Password($password)) {
            return show(0, '密码错误');
        }
        //登录成功
        $updateData = array(
            'lastlogintime' => time(),   //数据库中一般是int(10) 还能存很多年
            'lastlogip' =>ip2long($_SERVER['REMOTE_ADDR']),
            'loginnum'=>$data['loginnum']+1,
        );

        //进行上次登陆时间的更新操作
        M("Admin")->where('id=' . $data['id'])->save($updateData);
        //将用户信息保存在session中
        session('adminUser', $data);
        session('user_id', $data['id']);
        return show(1, '登陆成功');
    }
}